//
//  MessageAudioRecoder.m
//  MobileOA
//
//  Created by liqing-mac on 14-2-26.
//  Copyright (c) 2014年 chenxiaojuan. All rights reserved.
//
#import "StorageEngine.h"
#import "MessageAudioRecoder.h"

@implementation MessageAudioRecoder

@synthesize avPlay = _avPlay;


-(id)init{
    if (self = [super init]) {
        
        int randon = (arc4random() % 100000000000) + 1;
        NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio_%d_iOS.aac", strUrl,randon]];
        NSLog(@"%@",url);
        [self audioSettingWithFileURL:url];
    }
    return self;
}
-(id)initWithFileURL:(NSURL *) url{
    if (self = [super init]) {
        urlPlay = url;
        [self audioSettingWithFileURL:url];
    }
    return self;
}
-(void)audioSettingWithFileURL:(NSURL *) url{
    
  
    //录音设置
    NSMutableDictionary *recordSetting = [[[NSMutableDictionary alloc]init] autorelease];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
     urlPlay = url;
    [urlPlay retain];

    NSError *error;
    //初始化
    recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [session setActive:YES error:&error];
    
    //开启音量检测
    recorder.meteringEnabled = YES;
  
    
}

- (void)downLoadAndPlayVoice:(NSString *)url
{
    if ([StorageEngine downloadNetFile:url])
    {
        NSString *path = [StorageEngine readloadNetFile:url];
        NSURL *urlurl = [NSURL fileURLWithPath:path];
        [self playRecordSoundWithURL:urlurl];
    }
}


- (void)playRecordSoundWithURL:(NSURL *)url
{
    if (self.avPlay.playing) {
        //[self.avPlay stop];
        return;
    }
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.avPlay = player;
    player.volume = 1;
    [player release];
    [self.avPlay play];
}

-(void)detectionVoice{
    [recorder updateMeters];//刷新音量数据
    [recorder averagePowerForChannel:0];
    [recorder peakPowerForChannel:0];
    
    double lowPassResults = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
    
     NSLog(@"lowPassResults %f",lowPassResults);
    int volue = 0;
       //最大50  0
    //图片 小-》大
    if (0<lowPassResults<=0.06) {
        volue = 1;
    }else if (0.06<lowPassResults<=0.13) {
       volue = 2;
    }else if (0.13<lowPassResults<=0.20) {
        volue = 3;
    }else if (0.20<lowPassResults<=0.27) {
       volue = 4;
    }else if (0.27<lowPassResults<=0.34) {
        volue = 5;
    }else if(0.34<lowPassResults<=0.41) {
        volue = 6;
    }else if (0.41<lowPassResults<=0.48) {
        volue = 7;
    }else if (0.48<lowPassResults<=0.55) {
        volue = 8;
    }else if (0.55<lowPassResults<=0.62) {
        volue = 9;
    }else if (0.62<lowPassResults<=0.69) {
        volue = 10;
    }else if (0.69<lowPassResults<=0.76) {
        volue = 11;
    }else if (0.76<lowPassResults<=0.83) {
        volue = 13;
    }else if (0.83<lowPassResults<=0.9) {
        volue = 13;
    }else {
        volue = 14;
    }
    NSLog(@"voice %d",volue);
    [self.delegate detectionVoiceWithRecoder:volue];
}
-(BOOL)startRecoder{
    
    //创建录音文件，准备录音
    if ([recorder prepareToRecord]) {
        //开始
        NSLog(@"开始录音");
        [recorder record];
    }else{
        return NO;
    }
     [timer invalidate];
    //设置定时检测
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
    return YES;
}
-(void)paseRecoder{
    [recorder pause];
    ispase = YES;
    NSLog(@"暂停录音");

}
-(void)continueRecoder{
    if(ispase){
        [recorder record];
        NSLog(@"继续录音");
        ispase = NO;
    }
}
-(NSURL *)completeRecoder{
    [recorder stop];
    [timer invalidate];
    NSLog(@"停止录音  %@",urlPlay);
    return urlPlay;
}


@end
